package base.http.rxandroid;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.tange.ai.iot.client.gnssa.Constants;
import com.tange.ai.iot.client.gnssa.bean.RespMsg;

import base.activity.BaseActivity;
import base.http.utils.ConsumerDialog;
import base.http.utils.SubscriberUtils;
import io.reactivex.subscribers.DisposableSubscriber;
import retrofit2.HttpException;

public class CustomDisposableForJava<T> extends DisposableSubscriber<T> {

    private boolean isShowToast = true;
    private Activity mContext = null;
    private ConsumerDialog dialog = null;
    private SubscriberUtils subcribers = SubscriberUtils.Companion.getInstance();
    //    private SubscriberUtils subcribers = new SubscriberUtils();
    private String TAG = "CustomDisposableForJava";
//    private val isNetworkAvailable: Boolean
//    get() {
//        val cm = mContext!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
//        val info = cm.activeNetworkInfo ?: return false
//        val network = info.state
//        return network == NetworkInfo.State.CONNECTED || network == NetworkInfo.State.CONNECTING
//    }

    public CustomDisposableForJava() {
        subcribers.addSubscriber(this);
    }


    public CustomDisposableForJava(Context mContext) {
        this.mContext =  (BaseActivity) mContext;
        subcribers.addSubscriber(this);
    }

    public CustomDisposableForJava(Context mContext, ConsumerDialog dialog) {
        this.mContext = (BaseActivity) mContext;
        this.dialog = dialog;
        subcribers.addSubscriber(this);
    }

    public CustomDisposableForJava(Context mContext, ConsumerDialog dialog, boolean isShowToast) {
        this.mContext = (BaseActivity) mContext;
        this.dialog = dialog;
        subcribers.addSubscriber(this);
        this.isShowToast = isShowToast;
    }

    @Override
    public void onNext(T t) {
        if (dialog != null) {
            dialog.dismiss();
        }
        if (!((RespMsg) t).code.equals(Constants.CODE_SUCCESS)) {

        }
    }

    @Override
    public void onError(Throwable e) {
        if (dialog != null) {
            dialog.dismiss();
        }
        if (e instanceof HttpException){
            try {
                String errorJson = ((HttpException) e).response().errorBody().string();
                Log.e(TAG, "onErrorJSON:" + errorJson);
            } catch (Exception err) {
                err.printStackTrace();
            }
        }
    }

    @Override
    public void onComplete() {
        if (dialog != null) {
            dialog.dismiss();
        }
        this.dispose();
    }

}
